<template>
  <div ref="pagination">
    <el-row v-if="pageFlag">
      <el-pagination
        v-model:currentPage="defaultPage.pageNo"
        :page-size="defaultPage.pageSize"
        :page-sizes="[10, 30, 50, 100, 300]"
        :total="defaultPage.total"
        background
        layout="total, prev, pager, next,sizes, jumper"
        @size-change="sizeChange"
        @current-change="currentChange"
      />
    </el-row>
  </div>
</template>

<script>
import { computed, inject, reactive, toRefs, onMounted } from "vue";

export default {
  name: "TablePage",
  setup(props) {
    const tableCrud = inject("tableCrud");
    const pageChange = inject("pageChange");
    const state = reactive({
      fiexd: false,
      pageFlag: Boolean,
      defaultPage: {
        total: 0, // 总页数
        pageNo: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
    });
    // 是否展示分页
    state.pageFlag = computed({
      get() {
        return tableCrud.pageFlag;
      },
    });
    onMounted(() => {
      //初始化分页
      pageInit();
    });
    const pageInit = () => {
      state.defaultPage.total = tableCrud.page.total || 0;
      state.defaultPage.pageNo = tableCrud.page.pageNo || 1;
    };
    // 页大小回调
    const sizeChange = (val) => {
      tableCrud.page.pageSize = val;
      pageChange();
    };
    // 根据分页条数设置合适的当前分页
    const pageSize = () => {
      // 向上取整得到页数(总条数 / 页条数) < 当前页
      if (
        Math.ceil(state.defaultPage.total / tableCrud.page.pageSize) <
        tableCrud.page.pageNo
      ) {
        tableCrud.page.pageNo--;
        pageSize();
      }
    };
    // 页码回调
    const currentChange = (val) => {
      tableCrud.page.pageNo = val;
      pageChange();
    };
    return {
      ...toRefs(state),
      sizeChange,
      currentChange,
      pageInit,
    };
  },
};
</script>
<style scoped lang="scss">
</style>
